#!/bin/bash
# 禁用swap分区
function disable_swap() {
   swapoff -a 
   sed -i -r  's@(.*swap.*)@#\1@' /etc/fstab   
}
# 关闭防火墙
function disable_firewalld() {
   systemctl disable --now firewalld 
}
# 关闭selinux
function disable_selinux() {
   sed -i 's@SELINUX=enforcing@SELINUX=disabled@' /etc/selinux/config
}
# 配置yum源
function config_yum() {
   # 挂载关盘
   mount /dev/sr0 /mnt/cdrom
   yum install wget yum-utils -y 
   # base
   wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
   # epel
   wget -O /etc/yum.repos.d/epel.repo https://mirrors.aliyun.com/repo/epel-7.repo
   # docker-ce
   yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
# kubernetes   
cat <<EOF > /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64/
enabled=1
gpgcheck=1
repo_gpgcheck=0
gpgkey=https://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg https://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
EOF
}
# 设置主机名
function set_hostname() {
   local HOSTNAME=$1
   echo $HOSTNAME > /etc/hostname 
}

# 安装包
function install_package() {
  yum install -y kubelet-1.22.15 kubeadm-1.22.15 kubectl-1.22.15
  yum install -y docker-ce-19.03.0-3.el7
}
# 配置镜像加速
function config_docker() { 
   mkdir /etc/docker 
cat <<EOF  > /etc/docker/daemon.json
{
  "registry-mirrors": ["https://40ugatfl.mirror.aliyuncs.com"],
  "exec-opts":["native.cgroupdriver=systemd"]
}
EOF
   systemctl enable --now docker 
   systemctl enable kubelet
}
function config_hosts() {
   while read -p "请输入你想添加到hosts的主机(eg: 192.168.25.140 master); q退出: " host node
   do 
      if [ ${host} == "q" ];
      then
        break
      fi
      sed -i "\$a${host} ${node}" /etc/hosts
   done
}
function main() {
   echo "-------------------初始化k8s安装环境-------------------"
   echo "即将开始。。。。"
   sleep 3
   disable_firewalld
   disable_swap
   disable_selinux
   config_yum
   set_hostname $1   
   config_hosts 
   install_package
   config_docker
   echo "初始化成功，即将重启。。。"
   sleep 3
   reboot
}
if [ $# == 0 ];
then
  echo usage: $0 HOSTNAME 
  exit 1
fi
main $1  $* 
